package com.mlnx.web.ui.controller;

import com.mlnx.common.entity.Response;
import com.mlnx.service.common.enums.ResponseEnum;
import com.mlnx.ui.entity.Group;
import com.mlnx.ui.pojo.form.GroupForm;
import com.mlnx.ui.service.GroupService;
import com.mlnx.ui.service.PatientService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.shan.spring.base.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@Api(value = "UI群组接口", tags = "UI群组接口")
@RestController
@RequestMapping("ui/group")
public class GroupController extends BaseController {

    @Autowired
    private GroupService groupService;
    @Autowired
    private PatientService patientService;

    @ApiOperation(value = "获取所有群组名称和群组人数")
    @GetMapping(value = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true)
    })
    public Response getGroupAndCount(@RequestParam("userId") Integer userId) {
        return result(groupService.getAllGroups(userId, false));
    }

    @ApiOperation(value = "获取所有群组名称和群组人数")
    @GetMapping(value = "/taizhou")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true)
    })
    public Response getTaizhouGroupAndCount(@RequestParam("userId") Integer userId) {
        return result(groupService.getAllGroups(userId, true));
    }

    @ApiOperation(value = "添加群组")
    @PostMapping(value = "")
    public Response addGroup(@Valid GroupForm groupForm) {
        Group group = new Group();
        group.setName(groupForm.getName());
        group.setUserId(groupForm.getUserId());

        groupService.save(group);

        return result(group.getId());
    }

    @ApiOperation(value = "修改群组名称")
    @PutMapping(value = "/{groupId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "群组名", required = true)
    })
    public Response editGroup(@PathVariable("groupId") Integer groupId, @RequestParam("name") String name) {
        Group group = new Group();
        group.setId(groupId);
        group.setName(name);

        groupService.updateById(group);

        return result();
    }

    @ApiOperation(value = "删除群组")
    @DeleteMapping(value = "/{groupId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupId", value = "群组ID", required = true)
    })
    public Response deleteGroup(@PathVariable("groupId") Integer groupId) {
        Integer count = patientService.getGroupPatientsCount(groupId);
        if (count != null && count > 0)
            return result(ResponseEnum.GroupNotEmpty);

        groupService.removeById(groupId);

        return result();
    }

}
